package com.dong.thread.threadbasic;

import java.util.concurrent.CountDownLatch;

/**
 * 乱序的验证
 * Disorder这个程序，证明乱序执行的确存在
 * （好吧，在我的机子(ThinkPad X1E)上还是没有跑出来，老师的跑出来了）
 * 为什么会乱序？主要是为了提高效率
 *
 * 参考链接：https://www.cnblogs.com/54chensongxia/p/12120117.html
 *
 * @author by jiweidong on 2021/11/25.
 */
public class T16_Ordering_Disorder {

    private static int x = 0, y = 0;
    private static int a = 0, b = 0;

    public static void main(String[] args) throws InterruptedException {

        for (long i = 0; i < Integer.MAX_VALUE; i++) {

            x = 0;
            y = 0;
            a = 0;
            b = 0;
            CountDownLatch latch = new CountDownLatch(Integer.MAX_VALUE);

            Thread one = new Thread(() -> {
                a = 1;
                x = b;
                latch.countDown();
            });

            Thread other = new Thread(() -> {
                b = 1;
                y = a;
                latch.countDown();
            });

            one.start();
            other.start();
            latch.await();
            String result = "第" + i + "次（" + x + "，" + y + "）";
            if (x == 0 && y == 0) {
                System.err.println(result);
                break;
            }
        }
    }
}
